package com.dongnan.hl7v2;

import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.HapiContext;
import ca.uhn.hl7v2.app.HL7Service;
import ca.uhn.hl7v2.llp.MinLowerLayerProtocol;
import ca.uhn.hl7v2.parser.ParserConfiguration;
import ca.uhn.hl7v2.parser.PipeParser;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class HL7Listener {

	private static int PORT_NUMBER  = 9090;
	private static HapiContext context = new DefaultHapiContext();


	public static void main(String[] args) throws Exception {

		if(args.length > 0){
			PORT_NUMBER = Integer.parseInt(args[0]);
		}
		try {
			ThreadPoolExecutor executor = new ThreadPoolExecutor(
			10, 100,
			30, TimeUnit.SECONDS,
			new ArrayBlockingQueue<Runnable>(100));
			executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

			MinLowerLayerProtocol mllp = new MinLowerLayerProtocol();
			mllp.setCharset("UTF-8");
			PipeParser pipeParser = PipeParser.getInstanceWithNoValidation();

			context.setLowerLayerProtocol(mllp);
			context.setExecutorService(executor);
			ParserConfiguration p =new ParserConfiguration();
			context.getParserConfiguration().setValidating(false);
			boolean useSecureConnection = false; // are you using TLS/SSL?
			HL7Service ourHl7Server = context.newServer(PORT_NUMBER, useSecureConnection);
			ourHl7Server.registerApplication(new LilianReceivingApplication());
			ourHl7Server.setExceptionHandler(new MyReceivingApplicationExceptionHandler());
			ourHl7Server.startAndWait();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
